import {
  Controller,
  Get,
  HttpCode,
  Post,
  Req,
  UploadedFile,
  UseGuards,
  UseInterceptors,
} from '@nestjs/common';
import { UploadService } from './upload.service';
import { FileInterceptor } from '@nestjs/platform-express';
import multer = require('multer');
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { extname, } from 'path';
import { Request } from 'express';
import { AuthGuard } from '@nestjs/passport';
@ApiTags('图片上传')
@Controller('upload')
export class UploadController {
  constructor(private readonly uploadService: UploadService) { }
  /**
   * 上传图片到 本地 和 oss
   * @param body
   */
  @Post('/uploadOSS')
  @UseInterceptors(
    FileInterceptor('file', {
      storage: multer.diskStorage({
        // 开启储存本地public
        destination: './public/image', // 指定保存图片的目录,
        filename: (req, file, cb) => {
          // 使用原始文件名作为保存文件名
          const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
          const extension = extname(file.originalname);
          cb(null, file.fieldname + '-' + uniqueSuffix + extension);
        },
      }),
    }),
  )
  @ApiOperation({ summary: 'oss图片上传', operationId: 'uploadOSS' })
  async uploadOSS(@UploadedFile() file: any, @Req() request: Request): Promise<any> {
    return {
      filename: file.filename,
      url: `/public/image/${file.filename}`
    }
  }

  @HttpCode(200)
  @Get('/getTemporaryCredentials')
  @ApiOperation({ summary: '获取 OSS 临时访问授权', operationId: 'getTemporaryCredentials' })
  @UseGuards(AuthGuard('jwt'))
  async getTemporaryCredentials() {
    return await this.uploadService.getTemporaryCredentials();
  }
}
